﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GalaSoft.MvvmLight;
using wp8nop.Common;
using System.Diagnostics;

namespace wp8nop
{
    public partial class Login : PhoneApplicationPage
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Accedi_Click(object sender, RoutedEventArgs e)
        {
            if (tbemail.Text.Trim() == "")
            {
                Toast.SendToast("Inserisci l'email");
                return;
            }

            if (tbpassword.Password.Trim() == "")
            {
                Toast.SendToast("Inserisci la password");
                return;
            }

            progress.IsIndeterminate = true;
            nopService.NopServiceClient client = new nopService.NopServiceClient();
            client.ValidateUserCompleted +=client_ValidateUserCompleted;
            client.ValidateUserAsync(tbemail.Text.Trim(), tbpassword.Password.Trim());
        }

        void client_ValidateUserCompleted(object sender, nopService.ValidateUserCompletedEventArgs e)
        {
            progress.IsIndeterminate = false;
            if (e.Error != null)
                Toast.SendToast("Si è verificato un errroe di comunicazione con i nostri server, provare più tardi");

            else
            {
                Debug.WriteLine("Result: " + e.Result.ToString());
                if (e.Result > 0)
                {
                    App.IDUtente = e.Result;
                    App.SaveAccount(tbemail.Text.Trim(), tbpassword.Password.Trim());
                    NavigationService.Navigate(new Uri("/SceltaPagamento.xaml", UriKind.Relative));
                }
                else
                {
                    Toast.SendToast("email o password errate");
                }
            }
        }

        private void Registrati_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Registrazione.xaml", UriKind.Relative));
        }
    }
}